<?php
/**
 * @version		$Id: manager.php 10381 2008-06-01 03:35:53Z yopensource $
 * @package		YOS
 * @subpackage	Crawler
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.model');

// Set the table directory
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

/**
 * Crawler Component link Model
 *
 * @package		Joomla
 * @subpackage	Content
 * @since 1.5
 */
class YOS_NewsModelLinkCheck extends JModel
{
	/**
	 * amMap data array
	 *
	 * @var array
	 */
	var $_data = null;	

	/**
	 * uri total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

	/**
	 * Constructor
	 *
	 * @since 0.9
	 */
	function __construct()
	{
		parent::__construct();

		global $mainframe,$option;
		
		//$context			= 'com_content.viewcontent';
		$filter_order		= $mainframe->getUserStateFromRequest( $option.'.linkcheck.filter_order', 		'filter_order', 	'id',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'.linkcheck.filter_order_Dir',	'filter_order_Dir',	'',				'word' );	
		$search 			= $mainframe->getUserStateFromRequest( $option.'.linkcheck.search', 			'search', 			'',				'string' );
		$search 			= JString::strtolower( $search );
		
		$cms				= $mainframe->getUserStateFromRequest( $option.'.linkcheck.cms',			'cms',			0,	'string' );	
	
		$limit				= $mainframe->getUserStateFromRequest($option.'.linkcheck.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart			= $mainframe->getUserStateFromRequest($option.'.linkcheck.limitstart', 'limitstart', 0, 'int');
		
		$this->setState('limit', $limit);
		$this->setState('limitstart',$limitstart);
		$this->setState('cms',$cms);
		$this->setState('search',$search);		

		// Get the filter request variables
		$this->setState('filter_order', 	$filter_order);
		$this->setState('filter_order_dir', $filter_order_Dir);
	}
	
	function getTotal()
	{
		// Lets load the total nr if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}
	
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}
	
	
	function getData(){
		$pop	= JRequest::getBool('pop');
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			if ($pop) {
				$this->_data = $this->_getList( $query );
			} else {
				$this->_data = $this->_getList( $query, $this->getState('limitstart'), $this->getState('limit') );
			}
		}

		return $this->_data;
	}
	
	function _buildQuery(){
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildWhere();
		$orderby	= $this->_buildOrderBy();

		$config 	= &JComponentHelper::getParams('com_yos_news_crawler');
		$data_type 	= $config->get('data_type');	
	
		//Get Events from Database
		$query = 'SELECT c.* FROM #__yos_content_link AS c '							
				. $where
				. $orderby
				;	
		return $query;		
	}
	
	function _buildWhere( )
	{
		$db						=	& JFactory::getDBO();		
		$search					=	$this->getState('search');
		$cms					=	$this->getState('cms');
		
		$where = array();
		if ( $search ) {
			$where[] = 'link LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}		
		// cms filter
		if ($cms) {
			$where[] = 'cms = ' . $db->Quote($cms);
		}		
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );		
		return $where;
	}
	
	function _buildOrderBy()
	{
		$filter_order		=	$this->getState('filter_order');
		$filter_order_Dir	=	$this->getState('filter_order_dir');
		
		$orderby 	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir .', id';
		
		return $orderby;
	}
	
	function getLists(){
		
		// table ordering
		$lists['order_Dir']	= $this->getState('filter_order_dir');
		$lists['order']		= $this->getState('filter_order');
		
		// search filter
		$lists['search']= $this->getState('search');		
		
		$filter		= null;
		
		$config 	= &JComponentHelper::getParams('com_yos_news_crawler');
		$data_type 	= $config->get('data_type');		
	
		$arrCms=array();
		$arrFolder=JFolder::listFolderTree(JPATH_COMPONENT.DS.'cms','',1);
		foreach ($arrFolder as $value) {
			$cms=new stdClass();
			$cms->text=ucfirst($value['name']);
			$cms->value=$value['name'];
			$arrCms[]=$cms;
		}
			$active=$this->getState('cms');
			$option[] 	= JHTML::_('select.option', '0', '- '.JText::_('Select cms').' -');
			$option = array_merge($option, $arrCms);			
			$cms = JHTML::_('select.genericlist',  $option, 'cms', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $active);		
		$lists['cms']=$cms;
		
		return $lists;
	}	
	
	function removelink(){
		// Initialize variables
		$db 	=& JFactory::getDBO();
		$cid 	= JRequest::getVar('cid', array(0), 'post', 'array');
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a Link to delete', true ));
		}

		$cids = implode( ',', $cid );

		if (count( $cid )) {
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__yos_content_link'
			. ' WHERE id IN ( '.$cids.' )'
			;
			$db->setQuery( $query );			
			if (!$db->query()) {
				JError::raiseError( 500, $db->stderr() );
				return false;
			}
		}
	}
	function removelinkarticle()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db 		=& JFactory::getDBO();
		$cid 		= JRequest::getVar('cid', array(0), 'post', 'array');
		$nullDate	= $db->getNullDate();

		if (count($cid) < 1) {
			$msg =  JText::_('Select an item to delete');
			$mainframe->redirect('index.php?option='.$option.'&task=linkcheck', $msg, 'error');
		}
		
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
		$ycl_row =& JTable::getInstance('yos_content_link','Table');
		foreach ($cid as $id)
		{
			if ($id==0) {
				$msg =  JText::_('Select an item to delete');
				break;
			}
			$ycl_row->load($id);
			
			$className='YOS_'.ucfirst($ycl_row->cms).'_article';
			
			if (!class_exists($className)) {
				require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.$ycl_row->cms.DS.'article.php');
			}			
			
			$article=new $className($ycl_row->articleid);
			if ($article->msg) {
				return $article->msg;
			}
			
			if($msg=$article->deleteArticle())
			{
				$msg = JText::sprintf('Link(s), Article(s) deleted', count($cid));
				$ycl_row->delete();
			}else {
				$msg=$article->msg;
				$mainframe->redirect('index.php?option='.$option.'&task=linkcheck', $msg, 'error');
			}
		}
		return $msg;
	}
	
}